<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/2/20
 * Time: 18:32
 */

namespace think\addons;

use think\facade\Config;
use think\exception\HttpException;
use think\facade\Hook;
use think\Loader;
use think\facade\Request;
class Route
{
    public function execute($addon = null, $controller = null, $action = null){
        $request = Request::instance();
        // 是否自动转换控制器和操作名
        $convert = Config::get('app.url_convert');
        $filter = $convert ? 'strtolower' : 'trim';

        $addon = $addon ? trim(call_user_func($filter, $addon)) : '';
        $controller = $controller ? trim(call_user_func($filter, $controller)) : 'index';
        $action = $action ? trim(call_user_func($filter, $action)) : 'index';



        if (!empty($addon) && !empty($controller) && !empty($action)) {
            $info = get_addon_info($addon);

            if (!$info) {
                return  dd(404,'没有这个插件');
            }
            if (!$info['state']) {
                return dd(500,'插件被禁用');
            }
            $dispatch = $request->dispatch();
            // 设置当前请求的控制器、操作
            $request->controller($controller);
            $request->action($action);
            // 监听addon_module_init
           // Hook::listen('addon_module_init', $request);

            $class = get_addon_class($addon, 'controller', $controller);

            if (!$class) {
                return  dd(404,'没有这个控制器');
            }

            $instance = new $class($request);

            $vars = [];
            if (is_callable([$instance, $action])) {
                // 执行操作方法
                $call = [$instance, $action];
            } elseif (is_callable([$instance, '_empty'])) {
                // 空操作
                $call = [$instance, '_empty'];
                $vars = [$action];
            } else {
                // 操作不存在
               return dd(404,'addon action '.$action.'()'.' not found '.get_class($instance) . '->' . $action . '()');
            }
            //Hook::listen('addon_action_begin', $call);
            return call_user_func_array($call, $vars);
        }

    }
}